package com.i5tong.dbviewerlibrary;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class DataViewerActivity extends Activity {

    private List<List<String>> tableRow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_viewer);

        String db_name = getIntent().getStringExtra("db_name");
        String table_name = getIntent().getStringExtra("table_name");
        setTitle(table_name);

        tableRow = new ArrayList<>();
        List<String> row = null;
        SQLiteDatabase db = openOrCreateDatabase(db_name, Context.MODE_PRIVATE, null);
        Cursor c = db.rawQuery("SELECT * FROM " + table_name.toLowerCase(), null);
        row = new ArrayList<>();
        for (String s : c.getColumnNames()) {
            row.add(s);
        }
        tableRow.add(row);

        if (c.moveToFirst()) {
            while (!c.isAfterLast()) {
                row = new ArrayList<>();
                for (int i = 0; i < c.getColumnCount(); i++) {
                    row.add(c.getString(i));
                }
                tableRow.add(row);
                c.moveToNext();
            }
        }

        TableLayout tableLayout = (TableLayout)findViewById(R.id.tab);
        tableLayout.removeAllViews();
        for(int i=0;i<tableRow.size();i++){
            List<String> r = tableRow.get(i);
            TableRow tableRow = new TableRow(this);
            for (int j = 0; j < r.size(); j++) {
                TextView columsView = new TextView(this);
                columsView.setText(r.get(j));
                columsView.setPadding(10, 5, 10, 5);
                tableRow.addView(columsView);
            }

            if (i==0){
                tableRow.setBackgroundResource(R.color.color1);
            }
            tableLayout.addView(tableRow);
        }
    }
}
